<template>
  <q-page class="cc-admin">
    <div class="col bg-white shadow-2 q-pa-md q-ma-sm">
      <q-table flat color="primary" class="cross_table" separator="cell" :columns="columns" :data="list" row-key="id" :pagination.sync="pagination" :visible-columns="group" @request="query" :rows-per-page-options="[10, 20, 50, 100]" selection="multiple" :selected.sync="selected">
        <template v-slot:top="table">
          <div class="row no-wrap full-width">
            <q-input clearable outlined dense placeholder="请输入关键字搜索" class="on-left" @input="query" debounce="500" v-model="key">
              <template #append>
                <q-btn flat round icon="search" color="primary" @click="query" :loading="loading">
                  <q-tooltip>搜索</q-tooltip>
                </q-btn>
              </template>
            </q-input>
            <q-space />
            <div class="q-gutter-xs row">
              <div class="q-gutter-xs">
                <q-btn class="" icon="mdi-cloud-download-outline" no-wrap color="primary" label="下载模板" @click="exportModelExcel" />
              </div>
              <table-top-btns label="算法设计题" modelName="questions" :showAdd="true" :table="table" :selected="selected" :importing="importing" :exporting="exporting" :importExcelUrlFull="importExcelUrlFull" :columns="columns" @groupChange="groupChange" @add="add" @importExcel="importExcel" @exportExcel="exportExcel"
                @showConfirm="showConfirm" />
            </div>
          </div>
        </template>
        <template #body-cell-content="props">
          <q-td key="content" :props="props" style="width: 500px">
            <div style="width: 500px" class="cc-word-wrap">{{ props.row.content }}</div>
          </q-td>
        </template>
        <template #body-cell-questionStem="props">
          <q-td :props="props" style="max-width: 800px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">{{ props.row.questionStem }}</q-td>
        </template>
        <template #body-cell-opt="props">
          <q-td :props="props" :auto-width="true">
            <q-btn flat round dense color="primary" icon="edit" @click="edit(props.row)"> <q-tooltip>编辑</q-tooltip></q-btn>
            <q-btn flat round dense color="primary" icon="mdi-content-copy" @click="copy(props.row)">
              <q-tooltip>复制</q-tooltip>
            </q-btn>
            <btn-del label="简答题" @confirm="del(props.row)" />
          </q-td>
        </template>
      </q-table>
    </div>
    <q-dialog maximized flat persistent ref="dialog">
      <q-form @submit="submit" class="dialog_card column">
        <h5 class="view_title justify-between q-px-md">
          {{ editType }}简答题
          <q-btn dense outline round icon="clear" size="sm" v-close-popup />
        </h5>
        <q-scroll-area class="col">
          <div class="row q-col-gutter-x-md dialog_form q-pa-md">
            <div class="col-4">
              <q-select v-model="form.categorys" :options="categoryOptions" clearable multiple label="请选择分类" />
            </div>
            <div class="col-12">
              <h5>题干：</h5>
              <q-input outlined dense v-model="form.questionStem" type="textarea" />
              <div class="col-12" v-if="!form.viedoUrl">
                <h5>文件上传：</h5>
                <q-uploader url="http://127.0.0.1:9008/weather-api/upload" :headers="headers" field-name="uploadFile" label="文件上传" @uploaded="uploadResult2" color="purple" square flat bordered style="max-width: 300px" />
              </div>
              <div style="display: flex; align-items: center">
                <div class="q-video" style="margin-top: 10px" v-if="form.viedoUrl">
                  <viewer class="label-list q-mb-sm" style="max-height: 100px" ref="viewer" :options="options" :image="form.viedoUrl" v-if="form.viedoUrl" @inited="inited">
                    <img class="q-pl-sm" :src="form.viedoUrl" style="object-fit: contain; max-height: 100%; max-width: 150px" />
                  </viewer>
                </div>
                <div class="" style="margin-top: 10px">
                  <q-btn color="primary" icon="mdi-delete" label="删除" outline class="q-mx-md" @click="delVideo2" v-if="form.viedoUrl" />
                </div>
              </div>
            </div>

            <!-- 出题选项卡------------------------------------------------------------------------ -->
            <div class="col-12" style="height: 100%">
              <q-splitter v-model="splitterModel" style="height: 250px">
                <template v-slot:before>
                  <q-tabs v-model="tab" vertical class="text-teal">
                    <q-tab :name="item.indexNum" icon="" :label="`第${index + 1}题`" v-for="(item, index) in form.questionList" :key="item.indexNum" @click="log1" />
                    <q-btn dense flat text-color="light-blue-13" label="新增一题" icon="add" @click="addSub(form.questionList, subForm)" />
                    <q-btn dense flat text-color="light-blue-13" label="删除一题" icon="delete" @click="delSub(form.questionList)" />
                  </q-tabs>
                </template>

                <template v-slot:after>
                  <q-tab-panels v-model="tab" animated swipeable vertical transition-prev="jump-up" transition-next="jump-up">
                    <q-tab-panel :name="item.indexNum" v-for="(item, index) in form.questionList" :key="item.indexNum">
                      <div>
                        <div class="col-12">
                          <h5>题目：</h5>
                          <q-input outlined dense v-model="item.question" type="textarea" />
                        </div>
                        <div class="col-12">
                          <h5>答案：</h5>
                          <q-input outlined dense v-model="item.answer" type="textarea" :rows="15" />
                        </div>
                        <div class="col-12">
                          <h5>解析：</h5>
                          <q-input outlined dense v-model="item.analysis" type="textarea" />
                        </div>
                        <div class="col-12" v-if="!item.viedoUrl">
                          <h5>文件上传：</h5>
                          <q-uploader url="http://127.0.0.1:9008/weather-api/upload" :headers="headers" field-name="uploadFile" label="文件上传" @uploaded="uploadResult" color="purple" square flat bordered style="max-width: 300px" @added="startUpload(index)" />
                        </div>
                        <div style="display: flex; align-items: center">
                          <div class="q-video" style="margin-top: 10px" v-if="imageExtensions.includes(item.viedoUrl && item.viedoUrl.substring(item.viedoUrl.lastIndexOf('.')))">
                            <viewer class="label-list q-mb-sm" style="max-height: 100px" ref="viewer" :options="options" :image="item.viedoUrl" v-if="item.viedoUrl" @inited="inited">
                              <img class="q-pl-sm" :src="item.viedoUrl" style="object-fit: contain; max-height: 100%; max-width: 150px" />
                            </viewer>
                          </div>
                          <div class="q-video" style="margin-top: 10px" v-else>
                            <iframe :src="item.viedoUrl" frameborder="0" allowfullscreen height="100%" :ratio="4 / 3" />
                          </div>
                          <div class="" style="margin-top: 10px">
                            <q-btn color="primary" icon="mdi-delete" label="删除" outline class="q-mx-md" @click="delVideo" v-if="item.viedoUrl" />
                          </div>
                        </div>
                      </div>
                    </q-tab-panel>
                  </q-tab-panels>
                </template>
              </q-splitter>
            </div>
          </div>
        </q-scroll-area>
        <div class="row justify-center q-pa-md">
          <q-btn outline color="primary" icon="mdi-close-thick" label="关闭" v-close-popup @click="reset" />
          <q-btn class="q-mx-md" color="primary" icon="mdi-check-bold" label="提交" :loading="loading" type="submit" />
        </div>
      </q-form>
    </q-dialog>
    <confirm ref="confirmDialog" :msg="confirmMsg" @confirm="deleteBatch()" />
    <q-inner-loading :showing="loading">
      <q-spinner-gears size="50px" color="primary" />
    </q-inner-loading>
  </q-page>
</template>

<script>
import { IndexMixin } from 'boot/mixins';
import { getDictLabel } from 'boot/dictionary';
import confirm from 'components/confirm';
import Viewer from 'viewerjs';

export default {
  name: 'briefQuestion',
  mixins: [IndexMixin],
  components: {
    confirm,
  },
  data() {
    return {
      catalog: '0101',
      index: 0,
      tab: 0,
      splitterModel: 20,
      categoryOptions: [
        { label: '线性表', value: '1' },
        { label: '栈和队列', value: '2' },
        { label: '串', value: '3' },
        { label: '树与二叉树', value: '4' },
        { label: '图', value: '5' },
        { label: '查找', value: '6' },
        { label: '排序', value: '7' },
      ],
      subForm: {
        subjectId: '01',
        subjectText: '计算机',
        majorId: '0101',
        majorText: '数据结构',
        categorys: [], // 分类
        categoryIds: '',
        categoryIdsText: '',
        question: '',
        answer: '',
        analysis: '',
        viedoUrl: '',
      },
      fileMd5: '',
      showVideo: false,
      fileResult: '',
      headers: [
        {
          name: 'Authorization',
          value: localStorage.getItem('Authorization'), // 从localStorage中正确获取值
        },
      ],
      form: {
        questionStem: '',
        categorys: [],
        subjectId: '01',
        subjectText: '计算机',
        majorId: '0101',
        majorText: '数据结构',
        questionList: [
          {
            indexNum: 0, // 题号
            subjectId: '01',
            subjectText: '计算机',
            majorId: '0101',
            majorText: '数据结构',
            categorys: [], // 分类
            categoryIds: '',
            categoryIdsText: '',
            question: '',
            answer: '',
            analysis: '',
            viedoUrl: '',
          },
        ],
      },
      emptyForm: {
        questionStem: '',
        categorys: [],
        subjectId: '01',
        subjectText: '计算机',
        majorId: '0101',
        majorText: '数据结构',
        questionList: [
          {
            indexNum: 0, // 题号
            subjectId: '01',
            subjectText: '计算机',
            majorId: '0101',
            majorText: '数据结构',
            categorys: [], // 分类
            categoryIds: '',
            categoryIdsText: '',
            question: '',
            answer: '',
            analysis: '',
            viedoUrl: '',
          },
        ],
      },
      columns: [
        {
          name: 'index',
          align: 'center',
          label: '序号',
          field: 'index',
          // headerStyle: 'max-width:50px;min-width:50px;',
          // style: 'max-width:50px;min-width:40px;',
        },
        {
          name: 'questionStem',
          align: 'left',
          label: '题目',
          field: 'questionStem',
        },
        {
          name: 'opt',
          align: 'center',
          label: '操作',
          field: 'id',
        },
      ],
      showQuery: true,
      // uploadUrl: `${process.env.SERVER_URL}${process.env.BASE_URL}/sys/common/upload`,
      uploadUrl: `${process.env.SERVER_URL}${process.env.BASE_URL}/upload`,
      imgUrl: `${process.env.SERVER_URL}${process.env.BASE_URL}/sys/common/static`,
      url: {
        list: '/design/questionsList/list',
        add: '/design/questionsList/add',
        edit: '/design/questionsList/edit',
        copy: '/design/questionsList/copy',
        delete: '/design/questionsList/delete',
        deleteBatch: '/design/questionsList/deleteBatch',
        exportXlsUrl: '/design/questionsList/exportXls',
        importExcelUrl: '/design/questionsList/importExcel',
        exportModelXls: '/design/questionsList/exportModelXls',
      },
    };
  },
  methods: {
  exportExcel(fileName) {
      if (!fileName || typeof fileName !== 'string') {
        fileName = '导出文件';
      }
      this.exporting = true;
      console.log(this.selected);
      this.$downFile(this.url.exportXlsUrl, {

        choiceQuestions: this.selected.map((item) => item.id).join(','),
        key: this.key,
        catalog: this.catalog,

      }).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败');
          return;
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), `${fileName}.xls`);
        } else {
          const url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }));
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', `${fileName}.xls`);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); // 下载完成移除元素
          window.URL.revokeObjectURL(url); // 释放掉blob对象
        }
      }).finally(() => {
        this.exporting = false;
      });
    },
    // 使用JSON.parse和JSON.stringify
    reset() {
      this.index = 0;
      this.tab = 0;
      this.form = JSON.parse(JSON.stringify(this.emptyForm));
    },
    log1() {
      console.log(this.form.questionList);
    },
    startUpload(index) {
      console.log(index);
      this.index = index;
    },
    addSub(dataList, subForm) {
      // 存储subForm副本，不直接存储对象
      dataList.push({ ...subForm });
      this.calcDataIndex(dataList);
    },

    calcDataIndex(dataList) {
      if (dataList && dataList.length > 0) {
        dataList.map((v, i) => {
          v.indexNum = i + 1;
          return v;
        });
      }
    },
    delSub(dataList) {
      if (dataList && dataList.length > 0) {
        dataList.pop();
      }
    },
    getDictLabel,
    initDict() { },
    uploadResult(info) {
      const fileResult = JSON.parse(info.xhr.response);
      this.fileResult = fileResult;
      this.form.questionList[this.index].viedoUrl = `http://127.0.0.1:9000${fileResult.url}`;

      this.showVideo = true;
    },
    uploadResult2(info) {
      const fileResult = JSON.parse(info.xhr.response);
      this.fileResult = fileResult;
      this.form.viedoUrl = `http://127.0.0.1:9000${fileResult.url}`;
    },
    delVideo() {
      this.$axios
        .post(`${process.env.SERVER_URL}${process.env.BASE_URL}/deleteVideo`, {
          url: this.form.questionList[this.index].viedoUrl,
        })
        .then((r) => {
          this.$info(r.module);
          this.form.questionList[this.index].viedoUrl = '';
        });
    },
    delVideo2() {
      this.$axios
        .post(`${process.env.SERVER_URL}${process.env.BASE_URL}/deleteVideo`, {
          url: this.form.viedoUrl,
        })
        .then((r) => {
          this.$info(r.module);
          this.form.viedoUrl = '';
        });
    },
  },
  mounted() { },
};
</script>

<style lang="stylus">
label
  span
    margin-top 10px
img
  width 100%
  height auto
  aspect-ratio 16/9
.q-splitter__before, .q-splitter__after
    display inline-table
</style>
